package com.api.gbhg.lbj.action;

import com.alibaba.fastjson.JSONObject;
import com.api.gbhg.huangwm.dao.ReplaceJingfeiDao;
import com.api.gbhg.lbj.dao.ReimbursementDao;
import com.api.gbhg.zengping.common.CommonDao;
import com.api.gbhg.zengping.dao.PropertyManagementCostDao;
import com.weaver.general.BaseBean;


import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.DetailTable;
import weaver.soa.workflow.request.RequestInfo;
import weaver.workflow.workflow.WorkflowVersion;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;


import static com.api.gbhg.lbj.tool.Tools.getsfkzsydwbxed;

/**
 * @author lbj
 * @version 1.0
 * @description: TODO 明细表金额扣减 归档节点
 * @date 2021/5/8 17:26
 */
public class AmountDeduction implements Action {
    private static final Logger logger = LoggerFactory.getLogger("gbhg");
    private final PropertyManagementCostDao pmc=new PropertyManagementCostDao();
    private  final ReimbursementDao rei= new ReimbursementDao();
    @Override
    public String execute(RequestInfo requestInfo) {

        //获取提交节点同步的数据 去和当前节点数据对比
        String workflowid = requestInfo.getWorkflowid();
        String requestid = requestInfo.getRequestid();
        logger.info("明细表金额扣减 归档节点>"+requestid);
        //标题
        String description = requestInfo.getDescription();
        //得到明细表名
        DetailTable[] detailTables = CommonDao.getDetailTables(requestInfo);

        //当前流程表名-类似 formtable_main_22
        String billTableName = requestInfo.getRequestManager().getBillTableName();

        RecordSet rs = CommonDao.selectByRequestId(new RecordSet(), billTableName, requestid);
        rs.next();
        String mainid = rs.getString("id");//主表id

        RecordSet recordSet = CommonDao.selectByDetailTable(detailTables[0].getTableDBName(), mainid);
        int size = recordSet.getArray().size();
        //logger.info("当前明细行数size"+size);
        Map<String, String>[] list = new HashMap[size];
        List<Map<String, String>> m1 = new ArrayList<>();//用于接收归档时的报销明细数据
        int i = 0;
        boolean b=true;
        boolean b2=true;
        String ysxm="";
        while (recordSet.next()){
            int count=0;
            list[i]=new HashMap<>();
            //预算项目id
            ysxm = recordSet.getString("ysxm");
            //同意报销金额
            String tybxje=recordSet.getString("tybxje");
            //申请报销金额
            String sqbxje=recordSet.getString("sqbxje");
            String zcqd = recordSet.getString("zcqd");
            String ysly = recordSet.getString("ysly");
            String fzysrfl = recordSet.getString("fzysrfl");
            String xzkmdm = recordSet.getString("xzkmdm");
            String bmjjzcfl = recordSet.getString("bmjjzcfl");
            String bxr = recordSet.getString("bxr");
            String nd = recordSet.getString("nd");
            String cxje = recordSet.getString("cxje");
            String zcdfczbkxm = recordSet.getString("zcdfczbkxm");
            String dw = recordSet.getString("szdlhsdw");
            String jbbm = rs.getString("jbbm");

            Map<String, String> com1 = new HashMap();
            com1.put("lcjlid", ysxm);//预算项目
            com1.put("bmjjzcfl", bmjjzcfl);//部门经济支出分类
            m1.add(com1);

            list[i].put("workflowid", workflowid);//workflowid
            list[i].put("bxr",bxr);//报销人
            list[i].put("cxje",cxje);//冲销金额
            list[i].put("lcjlid", ysxm);//预算项目i
            list[i].put("tybxje",tybxje);//申请报销金额
            list[i].put("money", sqbxje);//申请报销金额
            list[i].put("bmjjzcfl", bmjjzcfl);//部门经济支出分类
            list[i].put("zcqd", zcqd);//支出渠道
            list[i].put("ysly", ysly);//预算来源
            list[i].put("fzysrfl", fzysrfl);//非中央收入分类
            list[i].put("xzkmdm", xzkmdm);//选择科目代码
            list[i].put("nd", nd);//选择科目代码
            list[i].put("zcdfczbkxm", zcdfczbkxm);//地方财政拨款项目
            list[i].put("dw", dw);//单位
            list[i].put("jbbm", jbbm);//经办部门
            i++;
            //logger.info("申请报销金额:"+sqbxje+"同意报销金额:"+tybxje);
            // 修改状态-bxlcmc-bxlcjlid
            b = pmc.modifyJingfeiSpzt(ysxm,requestid,description);
            //添加报销流程明细记录
            Map<String,Object> data=new HashMap<>();
            //mainid
            data.put("mainid",mainid);
            //报销金额
            data.put("bxje",tybxje);
            //报销流程id
            data.put("bxlcid",requestid);
            //项目流程id
            data.put("xmlcid",ysxm);
            //项目流程名称  根据 ysxm 查==>查经费表
            RecordSet rsj=null;
            if(count==0){
                rsj = CommonDao.selectJingfei(ysxm);
                rsj.next();
            }
            //项目名称
            String xmmc = rsj.getString("xmmc");
            data.put("xmlcmc",xmmc);
            //部门经济支出分类
            data.put("bmjjzcfl",recordSet.getString("bmjjzcfl"));
            //政府经济支出分类
            data.put("zfjjzcfl",recordSet.getString("zfjjzcfl"));
            //备注
            data.put("bz","无备注");
            logger.info("data----:"+data.toString());
            b2 = pmc.addbxDetailRecord(data);
            count++;
        }

        //获取存档报销记录
        String querySql="select * from uf_bxsjjl where lcid="+requestid;
        RecordSet res = new RecordSet();
        res.execute(querySql);
        int size1 = res.getArray().size();
        //logger.info("提交后报销数据表SQL----uf_bxsjjl:"+querySql);
        //logger.info("提交节点后明细行数:"+size1);
        Map<String, String>[] list1 = new HashMap[size1];
        List<Map<String, String>> m2 = new ArrayList<>();//用于接收已经存档的报销明细数据
        int j=0;
        while (res.next()){
            String ysxm1 = res.getString("ysxm");//
            String sqbxje = res.getString("sqbxje");//
            String tybxje = res.getString("tybxje");//
            String bmjjfl = res.getString("bmjjfl");//
            String cxje = res.getString("cxje");//冲销金额

            Map<String, String> com2= new HashMap();
            com2.put("lcjlid", ysxm1);//预算项目
            com2.put("bmjjzcfl", bmjjfl);//部门经济支出分类
            m2.add(com2);

            list1[j]=new HashMap<>();
            list1[j].put("lcjlid", ysxm1);//预算项目
            list1[j].put("bmjjzcfl", bmjjfl);//部门经济支出分类
            list1[j].put("money", sqbxje);//申请报销金额
            list1[j].put("tybxje", tybxje.isEmpty()?sqbxje:tybxje);//同意报销金额
            list1[j].put("cxje", cxje);//冲销金额
            j++;
        }

        //huangwm
        Boolean b5=true;
        Boolean b6=true;
        RecordSetTrans rst = new RecordSetTrans();
        rst.setAutoCommit(false);
        //2023年12月15日 经费更新存在事务问题 先不做更新
//        try {
//            if (size>size1) {
//                logger.info("会计节点如有添加新行 需要释放");
//                b5=rei.queryJingfei(rst,list1,false,1);//释放冻结金额
//                b6=rei.queryJingfei(rst,list,true,0);//扣减当前最新明细数据
//            }else{
//                boolean boo = JSONObject.toJSONString(m1).equals(JSONObject.toJSONString(m2));
//                System.out.println(JSONObject.toJSONString(m1));
//                System.out.println(JSONObject.toJSONString(m2));
//                if(!boo){
//                    logger.info("明细内容变化 需要释放");
//                    b5=rei.queryJingfei(rst,list1,false,1);//释放冻结金额
//                    b6=rei.queryJingfei(rst,list,true,0);//扣减当前最新明细数据
//                }else{
//                    logger.info("明细内容符合 扣减");
//                    b6=rei.queryJingfei(rst,list,true,0);//扣减当前最新明细数据
//                }
//            }
//        }catch (Exception e){
//            rst.rollback();
//            //删除报销记录
//            rs.execute("DELETE FROM uf_bxjl_kj WHERE lcid="+requestid);
//            rs.execute("DELETE FROM uf_bxjl_kj_dt1 WHERE lcid="+requestid);
//            rs.execute("DELETE FROM uf_bxjl_kj_dt2 WHERE lcid="+requestid);
//            logger.info(requestid+":判断明细数据是否改动出现异常"+e.getMessage());
//            requestInfo.getRequestManager().setMessagecontent(requestid+":判断明细数据是否改动出现异常"+e.getMessage());
//            requestInfo.getRequestManager().setMessageid("1");
//            return FAILURE_AND_CONTINUE;
//        }


        boolean b4 = true;
        b4 = rei.jingfeilaiyuandonjie(rst,list, true);//核批的渠道来源扣减
        boolean b3=true;
        RecordSet rs1 = getsfkzsydwbxed(ysxm);
        rs1.next();
        String sfkzsydwbxed = rs1.getString("sfkzsydwbxed");
        String lcid = rs1.getString("lcid");
        BaseBean baseBean=new BaseBean();
        String BZ18Workflowid = WorkflowVersion.getActiveVersionWFID(baseBean.getPropValue("FormationWorkflowid", "BZ18Workflowid"));//读取配置文件
       // logger.info("是否控制使用单位报销额度:"+sfkzsydwbxed+",workflowid:"+lcid+",BZ18Workflowid:"+BZ18Workflowid);
        if (StringUtils.isNotBlank(sfkzsydwbxed)&&sfkzsydwbxed.equals("1")&&!lcid.equals(BZ18Workflowid)){
            b3 = rei.userQuotaFreezeDeduction(rst,list, true);
        }
        logger.info("b="+b+" b2="+b2+" b3="+b3+" b4="+b4+" b5="+b5+" b6="+b6);
        //if(!b||!b2||!b3||!b4||!b5||!b6){
        if(!b2||!b3||!b4||!b5||!b6){//由于b不影响预算  不做强制控制 2022年2月17日09:18:20
            rst.rollback();
            //删除报销记录
            rs.execute("DELETE FROM uf_bxjl_kj WHERE lcid="+requestid);
            rs.execute("DELETE FROM uf_bxjl_kj_dt1 WHERE lcid="+requestid);
            rs.execute("DELETE FROM uf_bxjl_kj_dt2 WHERE lcid="+requestid);
            ReplaceJingfeiDao replaceJingfei = new ReplaceJingfeiDao();
            RecordSet recordSet2 = CommonDao.selectByDetailTable(detailTables[0].getTableDBName(), mainid);
            while (recordSet2.next()){
                String ysxmid = recordSet.getString("ysxm");
                Map<String,Object> result = replaceJingfei.replace(ysxmid);
                boolean jingfei = (boolean) result.get("result1");
                boolean jingfeilaiyuan = (boolean) result.get("result2");
                logger.info("异常时更新jingfei信息 jingfei="+jingfei+" jingfeilaiyuan="+jingfeilaiyuan);
            }

            logger.info("============================归档后扣减金额出现错误，修改审批状态错误======================================");
            requestInfo.getRequestManager().setMessagecontent("归档后扣减金额出现错误，修改审批状态错误");
            requestInfo.getRequestManager().setMessageid("1");
            return FAILURE_AND_CONTINUE;
        }

        try {
            ReplaceJingfeiDao replaceJingfei = new ReplaceJingfeiDao();
            RecordSet recordSet2 = CommonDao.selectByDetailTable(detailTables[0].getTableDBName(), mainid);
            while (recordSet2.next()){
                String ysxmid = recordSet.getString("ysxm");
                Map<String,Object> result = replaceJingfei.replace(ysxmid);
                logger.info(JSONObject.toJSONString(result));
                boolean jingfei = (boolean) result.get("result1");
                boolean jingfeilaiyuan = (boolean) result.get("result2");
                if(!jingfei){
                    //删除报销记录
                    rs.execute("DELETE FROM uf_bxjl_kj WHERE lcid="+requestid);
                    rs.execute("DELETE FROM uf_bxjl_kj_dt1 WHERE lcid="+requestid);
                    rs.execute("DELETE FROM uf_bxjl_kj_dt2 WHERE lcid="+requestid);
                    rst.rollback();
                    requestInfo.getRequestManager().setMessagecontent("归档后重新计算额度失败 jingfei错误");
                    requestInfo.getRequestManager().setMessageid("1");
                    return FAILURE_AND_CONTINUE;
                }
                if(!jingfeilaiyuan){
                    //删除报销记录
                    rs.execute("DELETE FROM uf_bxjl_kj WHERE lcid="+requestid);
                    rs.execute("DELETE FROM uf_bxjl_kj_dt1 WHERE lcid="+requestid);
                    rs.execute("DELETE FROM uf_bxjl_kj_dt2 WHERE lcid="+requestid);
                    rst.rollback();
                    requestInfo.getRequestManager().setMessagecontent("归档后重新计算额度失败 jingfeilaiyuan错误");
                    requestInfo.getRequestManager().setMessageid("1");
                    return FAILURE_AND_CONTINUE;
                }
            }
        }catch ( Exception e){
            e.printStackTrace();
            //删除报销记录
            rs.execute("DELETE FROM uf_bxjl_kj WHERE lcid="+requestid);
            rs.execute("DELETE FROM uf_bxjl_kj_dt1 WHERE lcid="+requestid);
            rs.execute("DELETE FROM uf_bxjl_kj_dt2 WHERE lcid="+requestid);
            rst.rollback();
            requestInfo.getRequestManager().setMessagecontent("归档后重新计算额度异常");
            requestInfo.getRequestManager().setMessageid("1");
            return FAILURE_AND_CONTINUE;
        }

        rst.commit();
        return SUCCESS;
    }
}
